import logging
import time
from typing import Dict, Optional, Any
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from src.config.settings import API_CONFIG

class APIWrapper:
    """API调用封装"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.session = self._setup_session()
        self.base_url = API_CONFIG["base_url"]
        
    def _setup_session(self) -> requests.Session:
        """配置请求会话"""
        session = requests.Session()
        retries = Retry(
            total=API_CONFIG["max_retries"],
            backoff_factor=API_CONFIG["retry_delay"],
            status_forcelist=[500, 502, 503, 504]
        )
        session.mount('http://', HTTPAdapter(max_retries=retries))
        session.mount('https://', HTTPAdapter(max_retries=retries))
        return session
        
    def get(self, endpoint: str, params: Dict = None) -> Optional[Dict]:
        """发送GET请求"""
        try:
            url = f"{self.base_url}/{endpoint}"
            response = self.session.get(
                url,
                params=params,
                timeout=API_CONFIG["timeout"]
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            self.logger.error(f"API请求失败: {str(e)}")
            return None
